var stompClient = null;

function setConnected(connected) {
    $("#connect").prop("disabled", connected);
    $("#disconnect").prop("disabled", !connected);
    if (connected) {
        $("#conversation").show();
    } else {
        $("#conversation").hide();
    }
    $("#notice").html("");
}

function connect() {
    var socket = new SockJS('/endpoint-websocket'); //连接上端点(基站)
    stompClient = Stomp.over(socket);			//用stom进行包装，规范协议
    stompClient.connect({}, function (frame) {
        setConnected(true);
        // console.log('Connected: ' + frame);
        stompClient.subscribe('/topic/game_chat', function (result) {
            // console.info(result)
            showContent(JSON.parse(result.body));
        });
    });
}

function disconnect() {
    if (stompClient !== null) {
        stompClient.disconnect();
    }
    setConnected(false);
    console.log("Disconnected");
}

function sendName() {
    // stompClient.send("/app/chat", {}, JSON.stringify({'content': $("#content").val()}));
    stompClient.send("/app/broadcast", {}, JSON.stringify({'content': $("#content").val()}));
}

function showContent(body) {
    switch (body.code) {
        case '200': {
            $("#notice").html("<tr><td>" + body.data.text + "</td> <td>" + new Date().toLocaleString() + "</td></tr>");
            break;
        }
        default: {
            $("#notice").html("<tr><td>" + '桃李不言下自成蹊' + "</td> <td>" + new Date().toLocaleString() + "</td></tr>");
            break;
        }
    }

}


$(function () {
    // $("form").on('submit', function (e) {
    //     e.preventDefault();
    // });
    connect();
    $( "#connect" ).click(function() { connect(); });
    // $( "#disconnect" ).click(function() { disconnect(); });
    // $( "#send" ).click(function() { sendName(); });
});

